//
//  ZLPResultDetailViewController.m
//  TangYi
//
//  Created by dllo on 15/10/31.
//  Copyright © 2015年 赵连鹏. All rights reserved.
//

#import "ZLPResultDetailViewController.h"
#import "ZLPResultDetailModel.h"
#import "ZLPResultPicModel.h"
#import "ZLPResultDetailTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "ZLPDetailViewController.h"
#import "ZLPCommentTableViewCell.h"
#import "ZLPCommentModel.h"
#import "ZLPLikerCollectionViewCell.h"
#import "ZLPLikerModel.h"
#import <AFNetworking.h>

@interface ZLPResultDetailViewController ()<UITableViewDataSource, UITableViewDelegate, ZLPResultDetailTableViewCellDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) NSMutableArray *productArr;
@property(nonatomic, retain) NSMutableArray *picArr;
@property(nonatomic, retain) UICollectionView *collection;
@property(nonatomic, retain) NSMutableArray *likeArr;
@property(nonatomic, retain) NSMutableArray *commentArr;
@property(nonatomic, retain) UIView *headView;

@end

@implementation ZLPResultDetailViewController

- (void)dealloc {
    [_headView release];
    [_commentArr release];
    [_collection release];
    [_likeArr release];
    [_tableView release];
    [_productArr release];
    [_picArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"物品详情";
    
    [self createTableView];
    
//    [self isWlan];
    [self createData];
    
    [self createCollectionView];
    
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            
            [self createData];
            
        } else {
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];

        }
        
    }];
}

#pragma mark create方法
- (void)createCollectionView {
   
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(40, 40);
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 50) collectionViewLayout:layout];
    [self.headView addSubview:self.collection];
    self.collection.backgroundColor = [UIColor whiteColor];
    [_collection release];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    [self.collection registerClass:[ZLPLikerCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    
}

- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -35, WIDTH, HEIGHT + 35 + 24) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.showsVerticalScrollIndicator = NO;
}

- (void)createData {
    NSString *strURL = @"http://open3.bantangapp.com/comm/comments/list";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString stringWithFormat:@"app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&object_id=%@&os_versions=9.1&page=0&pagesize=10&track_device_info=iPhone6%%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&type_id=2&v=7", self.numID];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
    
        if (data != nil) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.productArr = [NSMutableArray array];
            ZLPResultDetailModel *productModel = [[ZLPResultDetailModel alloc] init];
            [productModel setValuesForKeysWithDictionary:dic[@"data"][@"product"]];
            [self.productArr addObject:productModel];
            [productModel release];
            
            self.picArr = [NSMutableArray array];
            self.picArr = [ZLPResultPicModel baseModelByArr:dic[@"data"][@"product"][@"pic"]];
            
            self.commentArr = [NSMutableArray array];
            self.commentArr = [ZLPCommentModel baseModelByArr:dic[@"data"][@"comments_list"]];
            
            self.likeArr = [NSMutableArray array];
            self.likeArr = [ZLPLikerModel baseModelByArr:dic[@"data"][@"likes_list"]];
            
            [self.tableView reloadData];
            [self.collection reloadData];

        } else {
            
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
            image.image = [UIImage imageNamed:@"outnetwork.png"];
            [self.view addSubview:image];
            [image release];
            
        }
        
        
    }];
}

#pragma mark tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        return self.productArr.count;
    } else {
        return self.commentArr.count;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        static NSString *reuse = @"reuse";
        ZLPResultDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ZLPResultDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        
        ZLPResultDetailModel *productModel = [[ZLPResultDetailModel alloc] init];
        productModel = self.productArr[0];
        cell.titleLabel.text = productModel.title;
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.picArr[0] pic]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.descLabel.text = productModel.desc;
        cell.priceLabel.text = [NSString stringWithFormat:@"￥ %@", productModel.price];
        cell.delegate = self;
        
        return cell;
    } else {
        static NSString *reuse = @"comment";
        ZLPCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ZLPCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
        }
        
        ZLPCommentModel *commentModel = [[ZLPCommentModel alloc] init];
        commentModel = self.commentArr[indexPath.row];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:commentModel.avatar] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.nameLabel.text = commentModel.username;
        cell.timeLabel.text = commentModel.datestr;
        cell.commentLabel.text = commentModel.conent;
        
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
//#error headerview  分区
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
        
        [self createCollectionView];
        
        return self.headView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 50;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZLPResultDetailModel *model = [[ZLPResultDetailModel alloc] init];
        model = self.productArr[indexPath.row];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
        CGRect rect = [model.desc boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + 460;
    } else {
        ZLPCommentModel *model = [[ZLPCommentModel alloc] init];
        model = self.commentArr[indexPath.row];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];
        CGRect rect = [model.conent boundingRectWithSize:CGSizeMake(375, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + 70;
    }
}

#pragma mark click方法
- (void)click {
    ZLPDetailViewController *detailVC = [[ZLPDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    
    ZLPResultDetailModel *model = [[ZLPResultDetailModel alloc] init];
    model = self.productArr[0];
    detailVC.url = model.url;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return WIDTH / 50;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPLikerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    
    [cell.avatarImage sd_setImageWithURL:[NSURL URLWithString:[self.likeArr[indexPath.row] avatar]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    return cell;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
